const axios = require('axios');
const iconv = require('iconv-lite');

class SimulationLogin {
  constructor(username, password) {
    this.username = username;
    this.password = password;
    this.cookie = '';
    this.params = {};
  }

 loginHtml() {
    let url = 'http://class.sise.com.cn:7001/sise/';
    return axios.get(url).then(res => {
      let params = {};// 需要post的数据
      let data = res.data;
      let match = data.match(/<input type="hidden" name="(.*)"  value="(.*)">/);
      params[match[1]] = match[2];
      match = data.match(/<input id="random"   type="hidden"  value="(.*)"  name="(.*)" \/>/);
      params[match[2]] = match[1];
      params['username'] = this.username;
      params['password'] = this.password;
      return Promise.resolve(params);
    });
  }

  checkLogin() {
    let url = 'http://class.sise.com.cn:7001/sise/login_check_login.jsp';
    return this.loginHtml().then(params => {
      let _params = params;
      return axios.get(url, {
        params: _params
      }).then(res => {
        let data = res.data;
        let match = data.match(/<script>(.*)<\/script>/);
        if (match[1] === `top.location.href='/sise/index.jsp'`) {
          this.cookie = res.headers['set-cookie'][0];
          return Promise.resolve(true);
        } else {
          return Promise.resolve(false)
        }
      });
    });
  }

  getStudentMessage() {
    return this.setParams().then(isLogin => {
      if (isLogin) {
        let url = `http://class.sise.com.cn:7001/SISEWeb/pub/course/courseViewAction.do?${this.params.message}`;
        return axios.get(url, {
          headers: {
            'Cookie': this.cookie
          },
          responseType: 'stream'
        }).then(res => {
          return new Promise((resolve, reject) => {
            if (resolve) {
              res.data.pipe(iconv.decodeStream('gbk')).collect((err, body) => {
                if (!err) {
                  let match = body.match(/<td height="16" class="td_left">\s*<div align="left">\s*(.*)\s*<\/div>\s*<\/td>/g);
                  match = match.map((item, index, arr) => {
                    return item.replace(/\s/g, '').match(/<tdheight="16"class="td_left"><divalign="left">(.*)<\/div><\/td>/)[1]
                  });
                  resolve({
                    code: 0,
                    student: {
                      number: match[0],
                      name: match[1],
                      grad: match[2],
                      major: match[3],
                      email: match[5],
                      avatar: `http://class.sise.com.cn:7001/sise/module/studentphoto/${match[2]}/${match[0]}.jpg`,
                      teacher: match[6],
                      assistant: match[7]
                    }
                  });
                }
              });
            }
          });
        });
      } else {
        return Promise.resolve({
          code: -1,
          message: '学号或密码错误'
        })
      }
    });

  }

  setParams() {
    let url = `http://class.sise.com.cn:7001/sise/module/student_states/student_select_class/main.jsp`;
    return this.checkLogin().then(isLogin => {
      if (isLogin) {
        return axios.get(url, {
          headers: {
            'cookie': this.cookie
          }
        }).then(res => {
          let body = res.data;
          let match = body.match(/SISEWeb\/pub\/course\/courseViewAction.do\?(.*)'/);
          this.params['message'] = match[1]
          return Promise.resolve(true);
        });
      } else {
        return Promise.resolve(false);
      }
    });
  }
}

module.exports = SimulationLogin;
